﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using Coolite.Ext.Web;
using EB = Sagacity.Entity.Build;
using System.Data;
using Sagacity.NC.Web.FormForm;

namespace Sagacity.NC.Form
{
    public partial class HostFormCommon : System.Web.UI.UserControl
    {
        FormHelper helper = null;

        #region 定义列表表单属性

        /// <summary>
        /// 此表单是否只读
        /// </summary>
        public bool ReadOnly = false;

        public ShowPlan ShowPlan { get; set; }

        public int WidthValue { get; set; }

        /// <summary>
        /// 登陆人员信息
        /// </summary>
        public Business.SysMange.FormUser CurrentUser { get; set; }

        public Sagacity.Entity.Build.RoleInfo Role { get; set; }

        /// <summary>
        /// 资源数据过滤条件
        /// </summary>
        private List<Sagacity.Entity.Query.FilterInfo> filters = new List<Sagacity.Entity.Query.FilterInfo>();
        public List<Sagacity.Entity.Query.FilterInfo> Filters { get { return filters; } set { filters = value; } }

        /// <summary>
        /// 需要添加的字段以及对应的值
        /// </summary>
        private Hashtable addFields = new Hashtable();
        public Hashtable AddFields { get { return addFields; } set { addFields = value; } }

        /// <summary>
        /// 默认字段
        /// </summary>
        private Hashtable fieldDefault = new Hashtable();
        public Hashtable FieldDefault { get { return fieldDefault == null ? new Hashtable() : fieldDefault; } set { fieldDefault = value; } }

        /// <summary>
        ///  显示是否保存
        /// </summary>
        private bool showSave = true;
        public bool ShowSave { get { return showSave; } set { showSave = value; } }
        /// <summary>
        /// 刷新按钮是否显示
        /// </summary>
        private bool showRefresh = true;
        public bool ShowRefresh { get { return showRefresh; } set { showRefresh = value; } }

        /// <summary>
        /// 日志按钮是否显示
        /// </summary>
        private bool showLogInfo = true;
        public bool ShowLogInfo { get { return showLogInfo; } set { showLogInfo = value; } }

        /// <summary>
        /// 是否显示panel1的滚动条AutoScroll
        /// </summary>
        private bool pnlScroll = false;
        public bool PnlScroll { get { return pnlScroll; } set { pnlScroll = value; } }
        /// <summary>
        /// 设置模型参数
        /// </summary>
        private List<Sagacity.Entity.Query.ParameterInfo> modelparams = new List<Sagacity.Entity.Query.ParameterInfo>();
        public List<Sagacity.Entity.Query.ParameterInfo> ModelParams { get { return modelparams; } set { modelparams = value; } }

        public int ResourceId { get; set; }

        public static string TableName { get; set; }

        public string TableKey { get; set; }

        /// <summary>
        /// 列过滤值
        /// </summary>
        public int ColFilterKey { get; set; }

        public string ColFilterIdentify { get; set; }

        public int MenuId { get; set; }

        public List<Coolite.Ext.Web.Observable> BtnControls = new List<Observable>();

        public int intState { get; set; }

        private bool assoEnable = true;

        /// <summary>
        /// 是否显示关联操作按钮
        /// </summary>
        public bool AssoEnable 
        {
            get 
            {
                return assoEnable;
            }
            set {
                assoEnable = value;
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            helper = new FormHelper(ColFilterKey, ColFilterIdentify, modelparams);
            helper._currentUser = CurrentUser;
            HidWidthValue.Value = WidthValue.ToString();
            if (!IsPostBack)
            {
                helper.showPlan = ShowPlan;
                helper.hasFieldDefault = fieldDefault;
                hidKey.Value = TableKey;
                hidResourceId.Value= ResourceId.ToString();
                
                panel1.AutoScroll = PnlScroll;
                FormShow(intState);
                InitBtnControls();

                hidSqlCases.Value = helper.InitSqlCase(tbSqlCase, ResourceId, winSqlForm, MenuSelfUpdate);
            }
        }

        protected void InitBtnControls()
        {
            btnAsso.Visible = assoEnable;

            if (ReadOnly) 
            {
                btnSave.Enabled = false;
            }

            Sagacity.Build.Role role = new Sagacity.Build.Role();
            List<EB.ModuleItemInfo> ms = role.GetModuleItemInfos(CurrentUser.LoginRole).FindAll(o => o.ParentId ==
                MenuId && o.State == 0).ToList();

            foreach (Coolite.Ext.Web.Observable c in BtnControls)
            {
                EB.ModuleItemInfo m = ms.Find(o => o.Name == c.ID);

                if (m != null)
                {
                    projectToolbar.Items.Add(c);
                }
            }
            SetButtonRight(ms);
        }

        /// <summary>
        /// 针对页面中按钮权限的操作
        /// </summary>
        protected void SetButtonRight(List<EB.ModuleItemInfo> ms)
        {
            if (MenuId == 0)
                return;

            foreach (EB.ModuleItemInfo mInfo in ms)
            {
                Control control = FindControl(mInfo.Name);
                if (control != null)
                    control.Visible = true;
            }
        }
        protected void Store_Refresh(object sender, StoreRefreshDataEventArgs e)
        {
            FormShow(0);
        }

        [AjaxMethod]
        public bool AddFormShow()
        {
            FormShow(1);
            return true;
        }

        /// <summary>
        /// 获取保存在HidXML中的数据
        /// </summary>
        [AjaxMethod]
        public bool SubmitForm()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(hidXML.Value.ToString());
            XmlNode xmlTableInfo = doc.SelectSingleNode("Root/TableInfo");
            string tableName = xmlTableInfo.Attributes["Name"].Value;
            string tablekey = xmlTableInfo.Attributes["KeyName"].Value;

            string state = hidExcuteState.Value.ToString();

            if (state == "1")
            {
                hidExcuteState.Value = GetExcuteState(tableName, tablekey) == true ? "1" : "0";
                XmlNode node = doc.SelectSingleNode("Root/TableInfo");
                node.Attributes["CurrentExcuteSate"].Value = hidExcuteState.Value.ToString();
            }
            if (state == "0")
            {
                XmlNode node = doc.SelectSingleNode("Root/TableInfo");
                node.Attributes["CurrentExcuteSate"].Value = hidExcuteState.Value.ToString();
            }


            string KeyId = "0";
            string msg = string.Empty;
            bool result = helper.SaveTableInfo(doc, true, hidSelect.Value.ToString(), out KeyId, ref msg);
            if (result == true)
            {
                Ext.Msg.Alert("注意", "保存成功！").Show();
                if (hidExcuteState.Value.ToString() == "0")
                {
                    hidSelect.Value = KeyId;
                    //try
                    //{
                    //    if (TableName.Equals("COMM_ORGANIZATION"))
                    //    {
                    //        bool flag = (new Business.OrgManage.Organization()).IntRgtproject(CurrentUser.LoginRole.Id, 3, Convert.ToInt32(KeyId));
                    //    }
                    //    hidExcuteState.Value = GetExcuteState() == true ? "1" : "0";

                    //    string paramentName = "";
                    //    if (ModelParams.Count != 0)
                    //        paramentName = ModelParams[0].ParameterName;
                    //    else if (Filters.Count != 0)
                    //        paramentName = Filters[0].FieldName;

                    //    ModelParams.RemoveAt(0);
                    //    Sagacity.Entity.Query.ParameterInfo param = new Sagacity.Entity.Query.ParameterInfo() { ParameterName = paramentName, RealValue = KeyId };
                    //    ModelParams.Add(param);
                    //}
                    //catch { }
                }
                hidSelect.Value = KeyId;
                hidExcuteState.Value = "1";
                return true;
            }
            else
            {
                Ext.Msg.Alert("注意", msg).Show();
            }
            return result;
        }


        /// <summary>
        ///数据在显示的时候必须要重新绑定XML文件
        ///并且在新增的时候，重新给出过滤条件不能用以前的过滤条件
        /// </summary>
        /// <param name="intState">用于区分新增还是显示数据</param>
        protected void FormShow(int intState)
        {
            string[] tableInfo = Business.SysMange.Common.GetKeyByResourceId(ResourceId);
            TableName = tableInfo[0].ToUpper();
            hidKey.Value=TableKey = tableInfo[1].ToUpper();
            string fieldInfo = "";
            //0表示显示出来信息
            //1表示新增数据的时候重新绑定XML
            if (intState.Equals(1))
            {
                //给出一个默认的主键编号为-1当查询不到的时候就为增加
                int temp = 0;
                //这儿调用方法获取到编号
                GetCodeXML();
                Filters = new List<Sagacity.Entity.Query.FilterInfo>();
                Filters.Add(new Sagacity.Entity.Query.FilterInfo(hidKey.Value, "=", temp.ToString()));
                helper.SetFormShow(Role, ResourceId, Filters, tableInfo[1].ToUpper(), this.pnlForm.Controls, out fieldInfo, true, otherContent);
                hidExcuteState.Value = "0";
                if (!string.IsNullOrEmpty(hidCode.Value.ToString()) && !string.IsNullOrEmpty(hidCodeName.Value.ToString()))
                {
                    string codeColumn = hidCodeName.Value.ToString();
                    string code = hidCode.Value.ToString();
                    TextField txtCode = pnlForm.FindControl("" + codeColumn + "") as TextField;
                    txtCode.Value = code;
                }
            }
            else
            {
                helper.SetFormShow(Role, ResourceId, Filters, tableInfo[1].ToUpper(), this.pnlForm.Controls, out fieldInfo, !IsPostBack, otherContent);
            }



            btnSave.Visible = ShowSave;
            btnRefresh.Visible = ShowRefresh;
            System.Text.StringBuilder builder  = new System.Text.StringBuilder();
            hidExcuteState.Value = GetExcuteState(tableInfo[0], tableInfo[1]) == true ? "1" : "0";

            builder.Append("<Root>");
            builder.Append("<TableInfo Name='" + tableInfo[0].ToUpper() + "' CurrentExcuteSate='" + hidExcuteState.Value.ToString() + "' KeyName='" + tableInfo[1].ToUpper() + "' CurrentUser='" + CurrentUser.Id + "' Resource='" + ResourceId + "' Log='true' />");
            builder.Append("<RuleFilter DataId='' Type='' />");
            builder.Append(fieldInfo);
            builder.Append("</Root>");

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(builder.ToString());

            //此处查找主键节点，要求使用第一个过滤条件，即主键过滤
            string query = string.Empty;
            if (Filters.Count != 0)
            {
                query = "Root/Fields/Field[@Name='" + Filters[0].FieldName.ToUpper() + "']";
                XmlNode key = doc.SelectSingleNode(query);
                key.Attributes["Value"].Value = Filters[0].FieldValue.ToString();
                hidSelect.Value = Filters[0].FieldValue + "$";
            }
            else if (ModelParams.Count != 0)
            {
                query = "Root/Fields/Field[@Name='" + ModelParams[0].ParameterName.ToUpper() + "']";
                XmlNode key = doc.SelectSingleNode(query);
                key.Attributes["Value"].Value = ModelParams[0].RealValue.ToString();
                hidSelect.Value = ModelParams[0].RealValue + "$";
            }
         
            //如果隐藏域parent不为空那么就把它添加到hastable中，这个是获得当前节点的父级名称和父级编号
            if (!string.IsNullOrEmpty(this.hidParentValue.Value))
            {
                string[] parent = hidParentValue.Value.Split(new char[] { '$' });


                AddFields["" + parent[0].ToString() + ""] = parent[1].ToString();

                hidParentValue.Value = "";


            }


            XmlNode fields = doc.SelectSingleNode("Root/Fields");
            foreach (string f in AddFields.Keys)
            {
                fields.InnerXml += "<Field Name='" + f + "' ControlType='' IsHidden='True' EnableEdit='False' AddField='True' Value='" + AddFields[f].ToString() + "'/>";
            }
            hidXML.Value = doc.InnerXml;

        }

        protected bool GetExcuteState(string tableName, string tableKey)
        {
            string sql = string.Empty;
            if (filters.Count != 0 || ModelParams.Count != 0)
                sql = "select t." + tableKey + " from " + tableName + " t where t.";
            else
                sql = "select t." + tableKey + " from " + tableName + " t ";

            if (Filters.Count != 0)
            {
                sql += Filters[0].FieldName + " =" + Filters[0].FieldValue;
            }
            else if (ModelParams.Count != 0)
            {
                //当参数名和列名不符合时，会报错。
                foreach (Sagacity.Entity.Query.ParameterInfo p in ModelParams)
                {
                    sql += p.ParameterName + " =" + p.RealValue + " and ";
                }

               sql = sql.Remove(sql.LastIndexOf(" and "), 5);
            }
            
            return helper.mCommon.GetSQLResult(sql,null).Rows.Count > 0;
        }

        protected bool GetExcuteState(string tableName, string tableKey, string keyValue)
        {
            string sql = "select t." + tableKey + " from " + tableName + " t where t." + tableKey + " = " + keyValue;
            return helper.mCommon.GetSQLResult(sql,null).Rows.Count > 0;
        }

        /// <summary>
        /// 执行Sql方案
        /// </summary>
        /// <param name="exsqlcases"></param>
        /// <returns></returns>
        [AjaxMethod]
        public string ExcuteSqlCases(string exsqlcases) 
        {
            string [] sqlcaseIdstrs = exsqlcases.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            int [] sqlcaseIds = new int[sqlcaseIdstrs.Length];
            for (int i = 0; i < sqlcaseIdstrs.Length; i++) 
            {
                sqlcaseIds[i] = int.Parse(sqlcaseIdstrs[i]);   
            }
            return helper.ExcuteSqlCase(sqlcaseIds);
        }

        [AjaxMethod]
        public string NodeLoad(string nodeID, int fieldId,string nodeClickHandler)
        {
            return helper.NodeLoad(nodeID, fieldId, false,nodeClickHandler);
        }

        /// <summary>
        /// 取得关联字段的数据
        /// </summary>
        /// <param name="controlType"></param>
        /// <param name="fieldId"></param>
        /// <returns></returns>
        [AjaxMethod]
        public string GetFieldAssoDataInfo(string controlType, int fieldId, string paramName, string paramValue)
        {
            return helper.GetFieldAssoDataInfo(controlType, fieldId, paramName, paramValue);
        }

        #region 这儿是同一获得添加的编号


        /// <summary>
        /// 根据编号规则自动生成编号
        /// </summary>
        [AjaxMethod]
        public bool GetCodeXML()
        {
            bool flag = false;
            try
            {
                int CodeNum = 0;
                //生成的最终编号
                string code = "";
                //编号列名称
                string codeColumn = "";
                //如果是树，那么就要得到它的父级名称
                string parentName = "";
                foreach (string f in AddFields.Keys)
                {
                    parentName = f;
                }
                codeColumn = (new Sagacity.Build.Query.CodeRule()).GetCodeColumn(ResourceId);
                if (!string.IsNullOrEmpty(codeColumn))
                {
                    //如果隐藏域hidParentValue的值不为空时多半就是树形的数据了！
                    if (!string.IsNullOrEmpty(this.hidParentValue.Value))
                    {
                        //获取当前添加的是多少节点         
                        if (!string.IsNullOrEmpty(hidSelect.Value.ToString()))
                            GetCodeNum(parentName, hidSelect.Value.ToString().Split('$')[0].ToString(), ref CodeNum);

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(hidXML.Value.ToString());

                        XmlNodeList addFields = doc.SelectNodes("Root/Fields/Field[@Name='" + codeColumn + "'][@ControlType!='Button']");
                        for (int i = 0; i < addFields.Count; i++)
                        {
                            if (addFields[i].Attributes["Name"].Value == codeColumn)
                            {
                                code = (new Sagacity.Build.Query.CodeRule()).GetCode(ResourceId, CodeNum + 1, addFields[i].Attributes["Value"].Value);
                             
                            }

                        }
                    }
                    else
                    {
                        //否则就把它默认为非树形添加编号编号
                        code = (new Sagacity.Build.Query.CodeRule()).GetCode(ResourceId);
                      
                    }
                    hidCode.Value = code;
                    hidCodeName.Value = codeColumn;
                    flag= true;
                }
                if (code == "" || codeColumn == "")
                {
                    hidCode.Value = "";
                    hidCodeName.Value = "";
                    flag= false;
                }

            }
            catch (Exception)
            {
                flag= false;
            }
            return flag;
        }

        /// <summary>
        /// 循环获取数据
        /// 判断当前添加的节点是属于第几级节点
        /// 
        /// </summary>
        /// <param name="parenId">父级编号</param>
        protected int  GetCodeNum(string parentName,string parenId,ref int CodeNum)
        {

            string sql = "select t." + this.hidKey.Value;
            if (!string.IsNullOrEmpty(parentName))
                sql += "," + parentName;

            sql += " from " + TableName + " t where t." + hidKey.Value + " =" + parenId;
            DataTable dataTable = helper.mCommon.GetSQLResult(sql,null);
            if (dataTable.Rows.Count > 0)
            {
                CodeNum += 1;

                GetCodeNum(parentName,dataTable.Rows[0][1].ToString(), ref CodeNum);
            }

            return CodeNum;

        }


        #endregion

    }
}